-module (ham_server_http).

-include("emqttd.hrl").

-import(proplists, [get_value/2, get_value/3]).

-export([handle/1]).


handle(Req) ->
    try
        Path = string:to_lower(Req:get(path)),
        Method = Req:get(method),
        handle_funtion(Method, Path, Req)
    catch
        _:Reason ->
            lager:error("Reason:~p~n", [Reason]),
            Response1 = jsx:encode([{<<"code">>,3},{<<"message">>,<<"params not json">>}]),
            Req:ok({"text/plan",Response1})
    end.    


handle_funtion('POST', Path, Req) ->
    try
        [Path1] = string:tokens(Path,"/"),
        Mod = list_to_atom(Path1),
        lager:info("Mod is: ~p~n", [Mod]),
        case mod_handle(Mod,Req) of
            {ok, Rest} ->
                Response = jsx:encode(Rest),
                lager:debug("Reason:~p~n", [Rest]),
                Req:ok({"text/plan",Response});
            {error, Rest} ->
                lager:error("error:~p~n", [Rest]),
                Response = jsx:encode(Rest),
                Req:ok({"text/plan",Response})
        end
    catch
        _:Reason ->
            lager:error("Reason:~p ~p ~n", [Reason, erlang:get_stacktrace() ]),
            Response1 = jsx:encode([{<<"code">>,2},{<<"message">>,<<"params defect please check your params">>}]),
            Req:ok({"text/plan",Response1})
    end.

mod_handle(set_config,Req) ->
    Ip = Req:get(peer),
    Params = jsx:decode(mochiweb_request:parse_post1(Req)),
    lager:info("Params is: ~p~n", [Params]),
    set_config:handle(Ip,Params);  
mod_handle(Mod,Req) ->
    Params = jsx:decode(mochiweb_request:parse_post1(Req)),
    lager:info("Params is: ~p~n", [Params]),
    Mod:handle(Params).
